<template>
  <div class="shortcut_setting">
    <div class="section">
      <div class="types">
        <div class="types_tabs">
          <scroll-view class="scroll-view" :scroll-x="true" style="width: 100%; white-space: nowrap;display: flex;">
            <view class="item" v-for="(item, index) in typeList" :key="index" :class="active == index ? 'active' : ''"
              @click="selectTab(index, item)">
              {{ item.title }}
            </view>
          </scroll-view>
        </div>
        <div class="type_setting">
          <ImgT class="item_img" src="/imgs/serviceModal/groups_setting.webp" @click="openTypeSetting" alt="" />
        </div>
      </div>
      <div class="add_section">
        <div class="title">{{ t('add_quick_reply') }}：</div>
        <div class="add_input">
          <div class="input">
            <nut-input v-model="shortCuttext" :placeholder="t('add_quick_reply') + '~'">
              <template #left>
                <div class="search_item">
                  <SelectItem @change="onSelectChange" :active="params.value" :options="selectOptoions" />
                </div>
              </template>
            </nut-input>
          </div>
          <Btn height="37px" v-shrink-on-click width="80px" class="btn" @click="onAddLine">{{ t('add') }}</Btn>
        </div>
      </div>
      <div class="list">
        <div class="table">
          <div class="th">
            <template v-for="(item, i) in shorcutTableHeader" :key="i">
              <div class="line" v-if="i != 0"></div>
              <div class="td" :class="'td-' + item.size">{{ item.title }}</div>
            </template>
          </div>
          <scroll-view class="main_content">
            <div class="tr" v-for="(row, index) in dataList" :key="index">
              <template v-for="(item, idx) in shorcutTableHeader" :key="item.key">
                <div class="line"></div>
                <div class="td shorcut_list_td" :class="'td-' + item.size" @click="setCurRowIndex(index)">
                  <SelectItem v-if="idx === 0" @change="onRowSelectChange" :active="row.qhcid" :options="selectOptoions" />
                  <!-- 官方的不能编辑 -->
                  <nut-input v-if="idx === 1 && !row?.deviceid" v-model="row.content" :disabled="true"
                    :placeholder="t('chat_page_edit')" />
                  <nut-input v-if="idx === 1 && row?.deviceid" v-model="row.content" :disabled="!state.editing"
                    :placeholder="t('chat_page_edit')" />
                  <nut-switch v-if="idx === 2" v-model="row.istop" :disable="!state.editing" :active-value="1"
                    :inactive-value="2" inactive-color="#130a34" active-color="#1DAC77" />
                  <!-- 自动回复只能有一个 -->
                  <nut-switch v-if="idx === 3" :disable="!state.editing" @click="autospChange(row, index)"
                    v-model="row.isautorsp" :active-value="1" :inactive-value="2" inactive-color="#130a34"
                    active-color="#1DAC77" />
                  <div v-if="idx === 4 && row.deviceid" style="color: brown;" @click="onDeleteLine(row, index)">
                    {{ t('delete') }}</div>
                </div>
              </template>
            </div>
            <nut-empty v-if="!loading1 && !dataList?.length" :description="t('nomore_data')"></nut-empty>
          </scroll-view>
        </div>
        <div class="submit_btn">
          <Btn height="38px" v-if="!state.editing" v-shrink-on-click width="156px" class="submit edit"
            @click="onEditDataList">
            {{ t('modify') }}</Btn>
          <Btn height="38px" v-if="state.editing" v-shrink-on-click width="156px" class="submit" @click="onSaveDataList">
            {{ $t('save') }}</Btn>
        </div>
      </div>
    </div>
    <!-- 类别管理 -->
    <Modal v-model:visible="showTypeSetting" @close=" getShortcutCatelist()" :title="$t('chat_page_category_man')"
      zindex="1000">
      <div class="add_type_box">
        <div class="content">
          <div class="add_type">
            <div class="text">{{ t('add_category') }}:</div>
            <div class="input">
              <nut-input v-model="typeName" :placeholder="t('add_category')">
              </nut-input>
            </div>
            <Btn height="27px" v-shrink-on-click width="68px" class="btn" @click="onAddTypeLine">{{ t('add') }}</Btn>
          </div>
          <!-- 表格 -->
          <div class="table">
            <div class="th">
              <template v-for="(item, i) in tableHeader" :key="item.key">
                <div class="line" v-if="i != 0"></div>
                <div class="td" :class="'td-' + item.size">{{ item.title }}</div>
              </template>
            </div>
            <scroll-view class="main_content shorcut_list_td">
              <div class="tr" v-for="(row, index) in state.shortCutTyptList" :key="index + row.title">
                <template v-for="(item, idx) in tableHeader" :key="item.key">
                  <div class="line"></div>
                  <div class="td" :class="'td-' + item.size">
                    <nut-input v-if="idx === 0" v-model="row.title" :disabled="!row.deviceid ? true : false"
                      :placeholder="t('chat_page_edit')" />
                    <div v-if="idx === 1">{{ row.num || 0 }}</div>
                    <div v-if="idx === 2 && (!row?.num && row.deviceid)" style="color: brown;"
                      @click="deleteTypeLine(row, index)">{{ t('delete') }}</div>
                  </div>
                </template>
              </div>
              <nut-empty v-if="!loading && !state.shortCutTyptList.length" :description="t('nomore_data')"></nut-empty>
            </scroll-view>
          </div>
          <div class="submit_btn">
            <Btn height="38px" v-shrink-on-click width="156px" class="submit" @click="onSaveTypeList">{{ $t('save') }}</Btn>
          </div>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, reactive, onMounted, watch } from 'vue';
import SelectItem from "@/components/SelectItem.vue"
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import protobuf from 'protobufjs';
import usechatHooks from './useHooks.ts';
import IWebsocket from '../chatWS.ts'
import { showToast } from "@nutui/nutui";
import { useRoute, useRouter } from 'vue-router';
const route = useRoute();
import { showDialog } from '@nutui/nutui'

import { storeToRefs } from 'pinia';
import { User } from '@/store/user';
const { roleInfo } = storeToRefs(User());
const router = useRouter();



const state: any = reactive({
  root: null,
  deviceID: roleInfo.value.id,// roleInfo.value.id,
  requestid: 5000, // 对方id
  todeviceid: 2655337, //对方设备ID
  shortCutTyptList: [],
  quickPhrasesList: [],
  editing: false,
  canGoBack: true
})
const { getShortcutCateMsg, getShortcutCatelist, getShortcutMsg, getShortcutlist, setShortcutList, setShortcutCateList, decodeContent }: any = usechatHooks(state)
// tabs
let active = ref(0)
const showTypeSetting = ref(false)
const typeList = computed(() => {
  params.value = state.shortCutTyptList[0]?.id
  console.log('shortCutTyptList', state.shortCutTyptList)
  let arr = [...state.shortCutTyptList]
  arr.unshift({ title: t('all'), id: '0' })
  return arr
})
let dataList = ref(state.quickPhrasesList);
let selectedTabId = ref(null);
let dataListCopy = ref(state.quickPhrasesList);
watch(() => state.quickPhrasesList, (n) => {
  if (n.length) {
    dataListCopy.value = n
    dataList.value = active.value === 0 ? n : dataListCopy.value.filter((it: any) => it.qhcid === selectedTabId.value)
  }
})
const selectTab = (index: any, item: any) => {
  selectedTabId.value = item.id
  active.value = index
  dataList.value = item.id === '0' ? [...dataListCopy.value] : dataListCopy.value.filter((it: any) => it.qhcid === item.id)
}
const openTypeSetting = () => {
  showTypeSetting.value = true
  typeName.value = ''
  getShortcutCatelist()
}
// 添加快捷用语
// const selectOptoions = [
//   { label: '充值', value: 1 },
//   { label: '来访', value: 2 },
// ]
const selectOptoions = computed(() => {
  let arr = []
  arr = state.shortCutTyptList.map((item: any) => {
    return {
      label: item.title,
      value: item.id
    }
  })
  return arr
})
const params: any = reactive({
  value: 0
})
const onSelectChange = (value: any) => { // 切换下拉
  params.value = value
}
const shortCuttext = ref('')
const rowIndex = ref(0)
const onAddLine = () => {
  const obj = {
    content: shortCuttext.value,
    mType: 16, // 16 新增，17 修改，18 删除
    qhcid: params.value, // 分类id
    istop: 2, //1 为置顶 其余值不置顶
    isautorsp: 2, //是否是自动回复 前端用的
  }
  if (!(obj.content.trim())) {
    showToast.fail(t('content_required') + '!')
    return
  }
  dataList.value.unshift(obj)
  shortCuttext.value = ''; // 清空
}

const onDeleteLine = async (row: any, index: any) => {
  if (!state.editing) return
  console.log('rowl', row)
  showDialog({
    title: t('tip'),
    content: t('confirm_delete'),
    okText: t('confirm'),
    cancelText: t('cancel'),
    onOk: async () => {
      if (row.id) {
        const params = {
          ...row,
          mType: 18, // 16 新增，17 修改，18 删除
        }
        setDataList(params);
      } else {
        dataList.value.splice(index, 1)
      }
    },
  })
}
const onEditDataList = () => {
  state.editing = true
}
const onSaveDataList = () => {
  // 先遍历校验再请求
  let cansave = true
  dataList.value.map((item: any) => {
    if (!item.content.trim()) {
      cansave = false
    }
  })
  if (!cansave) {
    showToast.text(t('content_required') + '!')
    return
  }
  let list = <any>[]
  // 在某分组中设置自动回复，源数据的自动回复都要变更：如果自动回复item变更，将之前总list的自动回复的找出来设置为0再push进dataList 
  if (isautorspId.value) {
    dataListCopy.value.map((item: any) => {
      if (item.isautorsp == 1 && item.id !== isautorspId.value) {
        item.isautorsp = 2
        list.push(item)
      }
    })
  }
  list = list.length > 0 ? [...list, ...dataList.value] : [...dataList.value];
  console.log(333333333, list, dataList.value)
  list.map((item: any) => {
    if (item.id) {
      const params = {
        ...item,
        mType: 17, // 16 新增，17 修改，18 删除
      }
      setDataList(params)
    } else {  // 这是新增的数据
      const params = {
        ...item,
        mType: 16,
      }
      setDataList(params)
    }
  })
}
// 新增编辑删除快捷语
const setDataList = (data: any) => {
  const params = {
    ...data
  }
  setShortcutList(params)
}

// 类别管理
const typeName = ref('')
const onAddTypeLine = () => {
  const obj = {
    title: typeName.value,
    mType: 20, // 20 新增，21 修改，22 删除
  }
  if (!(obj.title.trim())) {
    showToast.fail(t('content_required') + '!')
    return
  }
  state.shortCutTyptList.unshift(obj)
  typeName.value = ''; // 清空
}
const onSaveTypeList = () => {
  state.shortCutTyptList.map((item: any) => {
    if (item.id) {
      const params = {
        ...item,
        mType: 21, // 20 新增，21 修改，22 删除
      }
      setShortTypeList(params)
    } else {  // 这是新增的数据
      const params = {
        ...item,
        mType: 20, // 20 新增，21 修改，22 删除
      }
      setShortTypeList(params)
    }
  })
}
const deleteTypeLine = (row: any, index: any) => {
  console.log('rowl', row)
  showDialog({
    title: t('tip'),
    content: t('confirm_delete'),
    okText: t('confirm'),
    cancelText: t('cancel'),
    onOk: async () => {
      if (row.id) {
        const params = {
          ...row,
          mType: 22, // 20 新增，21 修改，22 删除
        }
        setShortTypeList(params);
      } else {
        state.shortCutTyptList.splice(index, 1)
      }
    },
  })
}
const setShortTypeList = (data: any) => {
  const params = {
    ...data,
  }
  setShortcutCateList(params)
}

const loading = ref(false)
const tableHeader = computed(() => {
  return [ // 表头
    { title: t('category'), key: 'type', size: 'x' },
    { title: t('quick_reply_count'), key: 'count', size: 's' },
    { title: t('operation'), key: 'options', size: 's' },
  ]
})

// 快捷语表格
const shorcutTableHeader = computed(() => {
  return [ // 表头
    { title: t('type'), key: 'type', size: 'x' },
    { title: t('quick_reply'), key: 'text', size: 'x' },
    { title: t('top'), key: 'top', size: 's' },
    { title: t('auto_reply'), key: 'auto_reply', size: 's' },
    { title: t('operation'), key: 'options', size: 's' },
  ]
})
const loading1 = ref(false)
const setCurRowIndex = (index: any) => {
  rowIndex.value = index
  console.log('rowindex', index)
}
const onRowSelectChange = (value: any) => { // 切换行下拉
  if (!state.editing) return
  dataList.value[rowIndex.value].qhcid = value
  // resetData()
}
const isautorspId = ref()
const autospChange = (row: any, index: any) => { // 切换行下拉
  // 遍历整个列表，确保其他行的isautorsp都被设为关闭状态(2)
  dataList.value.forEach((item: any, i: any) => {
    if (dataList.value[index].isautorsp == 1 && index == i) {
      isautorspId.value = row.id
    } else if (index !== i && dataList.value[index].isautorsp == 1) {  // 确保不修改当前行
      item.isautorsp = 2;  // 设置其他行为关闭状态
    }
  });
}
const onMessage: any = async (buffer: any) => {
  const decodeobj1 = decodeContent(buffer, 'Output');
  console.log("onMessage/Output output0 ", decodeobj1)
  state.messageType = decodeobj1.type
  if (decodeobj1.code && decodeobj1.code > 1000) {
    showToast.fail(t(decodeobj1.code));
    return;
  }
  switch (decodeobj1.type) {
    case 23://快捷语分类
      getShortcutCateMsg(decodeobj1)
      break;
    case 19://快捷列表数据
      getShortcutMsg(decodeobj1)
      break;
    case 16:
    case 17:
    case 18://快捷列表编辑
      getShortcutlist();
      showToast.text(t('operation_success'))
      if (!state.canGoBack) return;
      router.go(-1);
      state.canGoBack = false;
      setTimeout(() => state.canGoBack = true, 2000);
      break;
    case 20:
    case 21:
    case 22://快捷类型编辑
      showToast.text(t('operation_success'))
      // showTypeSetting.value = false
      getShortcutCatelist();
      break;

    default:
      break;
  }
}
// 编码发送参数
const encodeParams = (params: any, name: string) => {
  let item = state.root.lookupType(name)
  const errMsg = item.verify(params);
  if (errMsg) throw new Error(errMsg);
  const message = item.create(params);
  const buffer = item.encode(message).finish();
  return buffer;
}
const onOpen = () => {
  const type = 1; // PT_SIGN_IN
  const requestid = 5000;
  const singin = {
    deviceid: state.deviceID,//用户的roleid
    userid: state.deviceID,//用户的roleid
    token: 'mmssdfasd1155',// Local.get('user').token,//后期从另外一个项目中获取
  }
  const data = encodeParams(singin, 'SignInInput')
  const params = {
    type: type,
    requestid: requestid,
    data: data,
  };
  const encodedRequest = encodeParams(params, 'Input')
  IWebsocket.sendMessageHandler(encodedRequest);
}
onMounted(async () => {
  state.deviceID = Number(roleInfo.value.id || localStorage.getItem('deviceid'))
  // state.userData = JSON.parse(route.query.userInfo as string)
  // state.todeviceid = state.userData.Tdeviceid
  // state.type = route.query.type
  state.requestid = route.query.requestid
  // state.chatMessagesList = []
  // console.log('进入,selectedchatItem', state.userData)
  if (IWebsocket.instance == null) {
    IWebsocket.conectWebsocket()
  }
  state.root = await protobuf.load('/connect.ext.proto');
  onOpen()
  IWebsocket.resgisterHandler(onMessage)
  // 获取
  getShortcutCatelist()
  getShortcutlist()
})
</script>

<style lang="scss" scoped>
@import "../common/table.scss";

.shortcut_setting {
  margin-top: 10px;
  display: flex;
  flex-direction: column;
}

.section {
  display: flex;
  flex-direction: column;
  height: calc(var(--vh) * 100 - 65px - env(safe-area-inset-top));
  padding: 0 10px 0;
  color: #8e82c2;

  .types {
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: 36px;
    flex-grow: 0;
    padding: 5px 7.6px 5px 6px;
    border-radius: 12px;
    box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.39), 0 2px 2px 0 rgba(0, 0, 0, 0.34), 0 5px 3px 0 rgba(0, 0, 0, 0.2), 0 8px 3px 0 rgba(0, 0, 0, 0.06), 0 13px 3px 0 rgba(0, 0, 0, 0.01);
    background-image: radial-gradient(circle at 50% 0%, #4c36b3 0%, #3a2786 100%, #3c279a 0%);

    .types_tabs {
      width: 100%;
      overflow: hidden;

      .scroll-view {

        .item {
          display: inline-block;
          margin: 4px;
          font-size: 14px;
          color: #87a1ce;
          padding: 4px 10px;

          &.active {
            color: #fff;
            background: url(/imgs/home/btn_bg.webp) no-repeat;
            background-size: 100% 100%;
          }
        }
      }
    }

    .type_setting {
      margin-left: 4px;
      padding: 0 5px;
      border-left: 1px solid #201844;
      display: flex;
      align-items: center;
    }
  }

  .add_section {
    .title {
      margin-bottom: 10px;
      font-size: 14px;
      text-align: left;
      color: #fff;
    }

    .add_input {
      display: flex;
      justify-content: space-between;

      &:deep(.nut-input) {
        width: 264px;
        height: 38px;
        padding: 2px 2px;
        border-radius: 8px;
        border: solid 1px #322c59;
        background-color: #1f2032;
        line-height: 28px;

        input {
          &::placeholder {
            color: #8d84c5;
          }

        }
      }

      .btn {
        border-radius: 8px;
        overflow: hidden;
      }

      :deep(.search_item) {
        height: 32px;
        min-width: 72px;

        .select_item_dialog {
          .select_item_option {
            display: inline-block;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            width: 100%;
            padding: 6px;
          }
        }
      }

      :deep(.select_item) {
        .label {
          max-width: 80px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          display: inline-block;
        }
      }
    }
  }

  .list {
    flex-grow: 1;
    margin-top: 14px;
    margin-bottom: 14px;
    display: flex;
    flex-direction: column;
    overflow: auto;
    max-height: 100%;

    .table {
      min-height: 200px;
    }

    .main_content {
      .shorcut_list_td {
        :deep(.select_item) {
          width: 80px;
          height: 30px;
          padding: 0px 4px;

          span {
            display: inline-block;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 80px;
          }

          .select_item_option {
            display: inline-block;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            width: 100%;
            padding: 6px;
          }
        }

        :deep(.nut-input) {
          height: 32px;
          padding: 4px 10px;
          border-radius: 8px;
          border: solid 1px #322c59;
          background-color: transparent;

          input {
            &::placeholder {
              color: #8d84c5;
              font-size: 10px;
            }

          }
        }

        :deep(.nut-switch.nut-switch-base) {
          height: 16px;
        }
      }
    }
  }
}

.add_type_box {
  color: #fff;

  .content {
    display: flex;
    flex-direction: column;
    max-height: 80vh;
    padding: 10px 20px 0;

    .add_type {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 14px 0;

      .text {
        font-size: 14px;
        color: #fff;
      }

      &:deep(.nut-input) {
        width: 170px;
        height: 32px;
        padding: 4px 10px;
        border-radius: 8px;
        border: solid 1px #322c59;
        background-color: #1f2032;

        input {
          &::placeholder {
            color: #8d84c5;
          }

        }
      }
    }
  }

  :deep(.nut-input) {
    height: 32px;
    padding: 4px 10px;
    border-radius: 8px;
    border: solid 1px #322c59;
    background-color: transparent;

    input {
      &::placeholder {
        color: #8d84c5;
        font-size: 10px;
      }

    }
  }

  :deep(.nut-switch.nut-switch-base) {
    height: 16px;
  }

}

:deep(.nut-popup) {
  z-index: 1000 !important;
  background: red;
}

:deep(.nut-overlay) {
  z-index: 1000 !important;
}

.submit_btn {
  width: 100%;
  padding: 24px 0;
  display: flex;
  justify-content: space-around;

  .edit {
    background-image: url("/imgs/btn/edit_btn_bg.webp");
    background-size: 100% 100%;

    :deep(img) {
      opacity: 0;
    }
  }
}
</style>